
<template>
    <div class="app-container">

        <!-- 表格查询 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
            <el-form-item label="平台类型" prop="platformId">
                <el-select v-model="queryParams.platformId" placeholder="请选择平台类型" clearable>
                    <el-option
                        v-for="dict in platformList"
                        :key="dict.id"
                        :label="dict.platformName"
                        :value="dict.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="店铺编码" prop="shopCode">
                <el-input
                    v-model="queryParams.shopCode"
                    placeholder="请输入店铺编码"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="店铺名称" prop="shopName">
                <el-input
                    v-model="queryParams.shopName"
                    placeholder="请输入店铺名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="店铺简称" prop="shopNickName">
                <el-input
                    v-model="queryParams.shopNickName"
                    placeholder="请输入名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="状态" prop="enabled">
              <el-select v-model="queryParams.enabled" placeholder="请选择状态" clearable>
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
  
        <!-- 表头操作 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>

            <!-- <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    @click="handleDelete"
                >删除</el-button>
            </el-col>
            <el-col :span="3">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleUpload"
                >店铺导入</el-button>
            </el-col> -->
            <!-- <right-toolbar @queryTable="getList"></right-toolbar> -->
        </el-row>

        <!-- 表格数据 -->
        <vxe-table
            border
            stripe
            v-loading="loading" 
            ref="tableRef"
            size="small"
            header-align="center"
            :row-config="rowConfig"
            :column-config="columnConfig"
            @checkbox-change="checkboxChangeEvent"
            @checkbox-all="checkboxAll"
            @cell-click="cellClickEvent"
            :data="tableDataList"
        >
            <vxe-column type="seq" width="60" align="center" fixed="left" />
            <vxe-column field="shopCode" show-overflow="title" align="center" title="店铺编码" />
            <vxe-column field="shopName" show-overflow="title" align="center" title="店铺名称"  />
            <vxe-column field="shopNickName"  show-overflow="title" align="center" title="店铺简称" />
            <vxe-column field="platformName" show-overflow="title" align="center" title="平台类型" />
            <vxe-column field="remark" show-overflow="title" align="center" title="备注" />
            <vxe-column field="createTime"  show-overflow="title" align="center" title="创建时间" />
            <vxe-column field="enabled" show-overflow="title" align="center" title="状态" >
              <template #default="{ row }">
                <el-tag :type="row.enabled == '1' ? 'success' : 'danger'">{{ row.enabled == '1' ? '启用' : '禁用' }}</el-tag>
              </template>

            </vxe-column>
            <vxe-column width="180" align="center" title="操作" fixed="right">
                <template #default="{ row }">
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleUpdate(row)"
                    >
                        修改
                    </el-button>
                </template>
            </vxe-column>
        </vxe-table>

        <!-- 分页 -->
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
  
        <!-- 新增弹窗 -->
        <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="60%" append-to-body @close="cancel">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="店铺名称" prop="shopName">
                            <el-input v-model="form.shopName" placeholder="请输入名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="店铺编码" prop="shopCode">
                            <el-input v-model="form.shopCode" placeholder="请输入店铺编码" :disabled="form.id" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="平台类型" prop="platformId">
                            <el-select v-model="form.platformId" placeholder="请选择平台类型" clearable>
                                <el-option
                                    v-for="dict in platformList"
                                    :key="dict.id"
                                    :label="dict.platformName"
                                    :value="dict.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="店铺简称" prop="shopNickName">
                            <el-input v-model="form.shopNickName" placeholder="请输入店铺简称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
                    </el-form-item>
                </el-row>
                <!-- 状态 -->
                <el-row>
                    <el-form-item label="状态" prop="enabled">
                        <el-switch
                            v-model="form.enabled"
                        />
                    </el-form-item>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" v-if="form.id" @click="submitForm1">保 存</el-button>
                <el-button type="primary" v-if="!form.id" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
  
        <!-- 导入对话框 -->
        <!-- <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog> -->
    </div>
  </template>
  
  <script>
  import { 
    addShopBasic,
    listShopBasic,
    delShopBasic,
    editShopBasic,
   } from "@/api/mes/sales/shopBasic";
   import { listPlatforms } from "@/api/mes/sales/platform";
  // import { getToken } from "@/utils/auth";
  // import { listUser } from "@/api/system/user";
  // import {genCode} from "@/api/system/autocode/rule"
  // import baseInfo from "./components/baseInfo.vue";
  export default {
    name: 'ShopBasic',
    // components: { 
    //   baseInfo,
    // },
    data() {
      return {
        //自动生成编码
        autoGenFlag:false,
        title: '',
        open: false,
        loading: false,
        total: 0,
        form: {
          enabled: true,
        },
        rules: {
            shopCode:[{ required: true, message: '请输入店铺编码', trigger: 'blur' }],
            shopName:[{ required: true, message: '请选择店铺名称', trigger: 'blur' }],
            platformId:[{ required: true, message: '请选择平台', trigger: 'blur' }],
        },
        platformList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        tableDataList: [],
        vendorList: [],
        warehouseList: [],
        userList: [],
        activeName: '1',
        cellId: null, //当前选中单元格的id
        baseTotal: 0, //采购订单条数
        // 用户导入参数
        // upload: {
        //   // 是否显示弹出层（用户导入）
        //   open: false,
        //   // 弹出层标题（用户导入）
        //   title: "",
        //   // 是否禁用上传
        //   isUploading: false,
        //   // 是否更新已经存在的用户数据
        //   updateSupport: 0,
        //   // 设置上传的请求头部
        //   headers: { Authorization: "Bearer " + getToken() },
        //   // 上传的地址
        //   url: process.env.VUE_APP_BASE_API + "/mes/md/shop/importData"
        // },
        columnConfig: {
          drag: true,
          resizable: true,
          storage: true,
          sortConfig: {
            trigger: 'cell',
            remote: true
          },
          align: 'center',
          headerAlign: 'center'
        },
        rowConfig: {
          drag: true,
          keyField: 'id',
          isHover: true,
          isCurrent: true,
        },
        ids: [], //选中的条目
        bottomTableData: '', //采购订单状态
      }
    },
    created() {
      this.getList()
      listPlatforms({pageNum: 1, pageSize: 9999, enabled: 1}).then(response => {
        this.platformList = response.rows;
      })
    },
    methods: {
      getList(){
        this.loading = true;
        // this.poCheckStatusList = []
        // this.queryParams.poStatusList = this.queryParams.poStatusList?[this.queryParams.poStatusList]:null
        // this.queryParams.poCheckStatusList = this.queryParams.poCheckStatusList?[this.queryParams.poCheckStatusList]:null
        listShopBasic(this.queryParams).then(response => {
          this.tableDataList = response.rows;
          this.$nextTick(() => {
            this.$refs.tableRef.setCurrentRow(this.tableDataList[0]);
            // this.bottomTableData = this.tableDataList[0].bottomTableData;
          })
          if(response.rows?.length>0){
            this.cellId = response.rows[0].id;
          }
          this.total = response.total;
          console.log(response);
        }).finally(() => {
          this.loading = false;
        //   this.queryParams.poStatusList = this.queryParams.poStatusList?.join()
        //   this.queryParams.poCheckStatusList = this.queryParams.poCheckStatusList?.join()
        })
      },
      reset(){
        this.form = {
          enabled: true,
        };
        this.autoGenFlag = false;
        // this.$refs.form.resetFields();
      },
      handleAdd(){
        this.open = true;
        this.title = '新增';
        this.reset()
      },
      handleDelete(row){
        if(this.ids.length==0){
          this.$modal.msgError("请选择要删除的数据");
          return;
        }
        const ids = this.ids;
        this.$modal.confirm('是否确认删除该数据项？').then(function() {
          return delShopBasic(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleUpdate(row){
        console.log(row);
        this.title = '修改';
        this.reset();
        this.open = true;
        this.form = { ...row };
      },
      handleToExamine(row){
        console.log(row);
      },
      handleAntiAudit(row){
        console.log(row);
      },
      handleQuery(){
        this.queryParams.pageNum = 1;
        this.getList();
      },
      resetQuery(){
        this.resetForm("queryForm");
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          poCode: null,
          vendorNick: null,
          poStatusList: undefined,
          poCheckStatusList: undefined,
        },
        this.getList();
      },
      submitForm(){
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
                editShopBasic(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
            } else {
              // this.form.deliveryTime = this.parseTime(this.form.deliveryTime, '{y}-{m}-{d} {h}:{i}:{s}')
              addShopBasic(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        })
      },
      cancel(){
        this.$refs["form"].resetFields();
        this.open = false;
      },
      //自动生成编码
      // handleAutoGenChange(autoGenFlag){
      //   if(autoGenFlag){
      //     genCode('PURCHASE_ORDER_CODE').then(response =>{
      //       this.form.poCode = response;
      //     });
      //   }else{
      //     this.form.poCode = null;
      //   }
      // },
      cellClickEvent({row}){
        this.cellId = row.id;
        // this.bottomTableData = row.poStatus;
        this.handleClick({name:'1'})
        console.log(row);
      },
      checkboxChangeEvent(checked){
        this.ids = checked.records.map(item => item.id)
        console.log(checked.records, this.ids);
      },
      checkboxAll(checked){
        this.ids = checked.records.map(item => item.id)
        console.log(checked.records, this.ids)
      },
      handleClick(tab, event) {
        switch (tab.name) {
          case '1':
            console.log('基础信息');
            break;
          case '2':
            console.log('2');
            break;
          default:
            break;
        }
      },
      // 订单明细
    //   getBaseInfoList(params={pageNum:1,pageSize:10}){
    //     detailPurchaseOrder(this.cellId, params).then(response => {
    //       this.baseTotal = response.total;
    //       console.log(response);
    //     })
    //   },
      handleUpload(){
        this.upload.title = "数据导入";
        this.upload.open = true;
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      handlePrint(row){
        console.log(row, window.location);
        window.open(window.location.origin + window.location.pathname + '#/printTemplate?poId=' + row.id + '&type=in', '_blank');
      },
      submitForm1(){
       editShopBasic(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      },
      importTemplate(){
        window.open("/excel_templates/shop_templates.xls", "_blank"); 
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  /* 选中行的高亮颜色 */
  // .el-table__row.current-row {
  //   background-color: #f0f9eb !important; /* 绿色背景 */
  // }
  </style>